﻿@using Newtouch.Infrastructure;
@using Newtouch.HIS.Web.Core.Extensions;
@{
    ViewBag.Title = "StockInventory";
    Layout = "~/Views/Shared/_Index.cshtml";
}

<style>
    #btn_search {
        width: 50px;
        margin-left: 40px;
    }
</style>

<form id="form1">
    <div class="panel panel-default" style="margin-top:10px;">
        <div class="panel-heading">
            查询条件
        </div>
        <div style="padding: 2px;padding-right:20px;">
            <table class="form">
                <tr>
                    <th class="formTitle">日期：</th>
                    <td class="formValue" colspan="2">
                        <select id="ddlRQ" class="form-control"></select>
                    </td>
                </tr>
                <tr>
                    <th class="formTitle">关键字：</th>
                    <td class="formValue">
                        <input id="txtSRM" type="text" class="form-control" placeholder="拼音 代码 药品名称" />
                    </td>
                    <th class="formTitle">药品状态：</th>
                    <td class="formValue">
                        <select id="ddlYPZT" name="ddlYPZT" class="form-control">
                            <option value="-1">全部</option>
                            <option value="1">启用</option>
                            <option value="0">停用</option>
                        </select>
                    </td>
                    <th class="formTitle">药品类别：</th>
                    <td class="formValue">
                        <select id="ddlYPLB" class="form-control">
                            <option value="">全部</option>
                        </select>
                    </td>
                    <th class="formTitle">库存显示：</th>
                    <td class="formValue">
                        @Html.DropDownList("ddlKCXS", EnumKCXS.Bxsllslwl.ToDescSelectList(-1), new { @class = "form-control" })
                    </td>
                    <td class="formValue">
                        <input type="button" id="btn_search" class="btn btn-primary" value="查询" />
                    </td>
                </tr>
            </table>
        </div>
    </div>
    <div class="gridPanel">
        <table id="gridKCInfo"></table>
        <div id="gridPager" rel="form1"></div>
    </div>
</form>


@Html.Partial("_BottomButtonsView", new Newtouch.HIS.Web.Core.Models.BottomButtonViewModel()
{
    ShowKeyList = new int[] { 2, 3, 7, 8 },
    F2Text = "开始",
    F3Text = "结束",
    F7Text = "取消"
})

<script>
    var $gridKCInfo = $("#gridKCInfo");
    var lastRowId;
    var ObjArr_Load = new Array();
    $(function () {
        $(window).resize(function () {//浏览器窗口调整大小时重新加载jqGrid的宽
            initLayout("MyTabGrid");
        });
        gridKCInfo();//库存信息
        GetPDSJ();//获取盘点日期
        initialddlYPLBList();//获取药品类别
        $("#btn_search").click(function () {//绑定查询查询
            Search();
        });
    });

    //库存信息
    function gridKCInfo() {
        $gridKCInfo.dataGrid({
            autowidth: true,
            postData: getSearchPostData(),
            height: $(window).height() - 240,
            url: "",
            editurl: "clientArray",  //行编辑不向服务器提交数据
            onSelectRow_page: function (rowid) {
                if (rowid && lastRowId && rowid !== lastRowId) {   //&&: 相当于true/fase(判断是否有值)

                    $gridKCInfo.saveRow(lastRowId, null, null, null, function (callbackRowId) {//先保存处于编辑状态的那一行
                        GetYfbmYpComplexYpSlandDw(callbackRowId);//变更当前部门单位下的数量
                    }, null, null);
                }
                lastRowId = rowid;
                $gridKCInfo.jqGrid('editRow', rowid, true, null, null, null, null, function (callbackRowId) {
                    GetYfbmYpComplexYpSlandDw(callbackRowId);//变更当前部门单位下的数量
                    lastRowId = undefined;  //回调
                });
            },
            colModel: [
                { label: '药品代码', name: 'ypCode', width: 80, align: 'left' },
                { label: '药品名称', name: 'ypmc', width: 120, align: 'left' },
                { label: '规格', name: 'ypgg', width: 100, align: 'left' },
                { label: '理论数量(部门包装)', name: 'llsl', width: 110, align: 'left' },
                { label: '理论数量(最小包装)', name: 'llsl_zxbz', width: 110, align: 'left' },
                { label: '数量', name: 'deptSjsl', width: 70, align: 'center', editable: true },
                { label: '单位', name: 'deptdw', width: 50, align: 'left' },
                { label: '批号', name: 'ph', width: 100, align: 'center' },
                { label: '批次', name: 'pc', width: 150, align: 'left' },
                { label: '有效期', name: 'yxq', width: 100, align: 'left' },
                { label: '批发价', name: 'pfj', width: 80, align: 'left' },
                { label: '零售价', name: 'lsj', width: 80, align: 'left' },
                { label: '理论批发金额', name: 'llpfje', width: 80, align: 'left' },
                { label: '理论零售金额', name: 'lllsje', width: 80, align: 'left' },
                { label: '实际批发金额', name: 'sjpfje', width: 80, align: 'left' },
                { label: '实际零售金额', name: 'sjlsje', width: 80, align: 'left' },
                { label: '产地', name: 'ycmc', width: 120, align: 'left' },
                { label: '拼音', name: 'py', width: 100, align: 'left' },
                { label: 'pdmxId', name: 'pdmxId', hidden: true, align: 'left' },
                { label: 'zhyz', name: 'zhyz', hidden: true, align: 'left' },
                { label: '实际数量(部门包装)', name: 'sjslstr', hidden: true },
                { label: '实际数量(最小单位)', name: 'minSjsl', hidden: true },
                { label: '最小单位', name: 'zxdw', hidden: true }
            ],
            multiselect: false,
            pager: "#gridPager",
            sortname: 'CreateTime desc',
            viewrecords: true,
            gridComplete: function () {
                afterCompleteFunction();
            },
            onSelectRow: function (rowid) {
                $("#" + $.jgrid.jqID(rowid) + "_sjsl").focus();
            }
        });
    }

    //查询
    function Search() {
        var postdata = getSearchPostData();
        if (postdata) {
            $gridKCInfo.jqGrid('setGridParam', {
                postData: postdata, url: '/PharmacyDrugStorage/SelectInventoryInfoList'
            }).trigger('reloadGrid');
        }
    }

    //查询条件
    function getSearchPostData() {
        var pdsj = $("#ddlRQ").val();
        var pdId = $("#ddlRQ option:selected").attr('data-pdId');
        var srm = $("#txtSRM").val();
        var ypzt = $("#ddlYPZT").val();
        var yplb = $("#ddlYPLB").val();
        var kcxs = $("#ddlKCXS").val();
        if (!pdsj && !pdId) {
            return false;
        }
        return { pdsj: pdsj, pdId: pdId, srm: srm, ypzt: ypzt, yplb: yplb, kcxs: kcxs };
    };

    //加载第一次查询数据
    function afterCompleteFunction() {
        var rowIds = $("#gridKCInfo").jqGrid('getDataIDs');//Grid加载完成开启行内编辑   1.先获取所有行Id  2.遍历调用editRow方法
        for (var i = 0; i < rowIds.length; i++) {
            ObjArr_Load.push($("#gridKCInfo").jqGrid('getRowData', rowIds[i]));
            $("#gridKCInfo").jqGrid('editRow', rowIds[i], true, null, null, null, null, function (callbackRowId) {     //true: when set to true we can use [Enter] key to save the row and [Esc] to cancel editing.
            });

        }
    }

    //获取盘点时间
    function GetPDSJ() {
        $.najax({
            type: "POST",
            url: "/PharmacyDrugStorage/GetPDDateDropdownList",
            dataType: "json",
            success: function (ajaxresp) {
                //先清空，再填充
                $("#ddlRQ").empty();
                for (var i = 0; i < ajaxresp.data.length; i++) {
                    $("#ddlRQ").append('<option data-pdId=' + ajaxresp.data[i].pdId + '>' + ajaxresp.data[i].pdsj + '</option>');
                }
                Search();
            }
        });

    }

    //药品类别
    function initialddlYPLBList() {
        $("#ddlYPLB").bindSelect({
            url: "/PharmacyDrugStorage/GetMedicineCategoryList"
        });
    }

    //输入最小单位下的数量，变更当前部门单位下的数量
    function GetYfbmYpComplexYpSlandDw(callbackRowId) {
        var rowData = $("#gridKCInfo").jqGrid('getRowData', callbackRowId);
        $.najax({
            type: "POST",
            url: "/PharmacyDrugStorage/GetYfbmYpComplexYpSlandDw",
            dataType: "text",
            data: { sl: rowData.sjsl, ypCode: rowData.ypCode },
            success: function (ajaxresp) {
                $('#gridKCInfo').jqGrid('setCell', callbackRowId, 'sjslstr', ajaxresp);
            }
        });
    }

    //开始盘点
    function newtouch_event_f2() {
        $.najax({
            type: "POST",
            url: "/PharmacyDrugStorage/StartInventory",
            dataType: "json",
            success: function (ajaxresp) {
                if (ajaxresp != null && ajaxresp.data != null) {
                    $('<option data-pdId=' + ajaxresp.data.pdId + ' selected="selected">' + ajaxresp.data.pdsj + '</option>').insertBefore('#ddlRQ option:first');
                }
                Search();
            }
        });
    }

    //保存
    function newtouch_event_f8() {
        var rowIds = $("#gridKCInfo").jqGrid('getDataIDs');//获取所有行Id，遍历使编辑框处于保存状态

        //判断退数量
        for (var i = 0; i < rowIds.length; i++) {
            $("#gridKCInfo").saveRow(rowIds[i], null, null, null, function (callbackRowId) { }, null, null);
            var rowData = $("#gridKCInfo").jqGrid('getRowData', rowIds[i]);
            if (!rowData) {
                return false;
            }
            if ((rowData.deptSjsl.replace(/(^\s*)|(\s*$)/g, "") === "" && rowData.minSjsl.replace(/(^\s*)|(\s*$)/g, "") === "") ||
                (rowData.deptSjsl < 0 && rowData.minSjsl < 0) ||
                (isNaN(rowData.deptSjsl) && isNaN(rowData.minSjsl)) ||
                (rowData.deptSjsl === "" && rowData.minSjsl === "")) {
                $.modalAlert("项目（" + rowData.ypmc + "）实际数量应为自然数，请确认。", "warning");
                EnableInlineEditBox();//启用行内编辑框
                return false;
            }
        }
        var kcInfoJsonSave = $("#gridKCInfo").jqGrid('getRowData_AllLine');
        var objArrSave = new Array();
        $.each(kcInfoJsonSave, function () {//保存时将Grid的数据行放在新的数组中
            objArrSave.push(this);
        });
        var resultObjArr = new Array();
        //与页面加载的数组进行比对，将修改过的数据行放在resultObjArr中，传给后台
        for (var i = 0; i < objArrSave.length; i++) {
            if (objArrSave[i].deptSjsl !== ObjArr_Load[i].deptSjsl || objArrSave[i].minSjsl !== ObjArr_Load[i].minSjsl) {
                //resultObjArr.push({ pdmxId: objArrSave[i].pdmxId, sjsl: CalculationMinUnitNum(objArrSave[i].deptSjsl, objArrSave[i].minSjsl, objArrSave[i].zhyz) });
                resultObjArr.push({ pdmxId: objArrSave[i].pdmxId, sjsl: CalculationMinUnitNumNoOpen(objArrSave[i].deptSjsl, objArrSave[i].zhyz) });
            }
        }
        if (resultObjArr.length === 0) {
            $.modalAlert("没有需要保存的数据", 'warning');
            return false;
        }
        $.najax({
            type: "POST",
            url: "/PharmacyDrugStorage/SaveInventoryInfo",
            dataType: "json",
            data: { resultObjArr: JSON.stringify(resultObjArr), pdId: $("#ddlRQ option:selected").attr('data-pdId') },
            success: function (ajaxresp) {
                $.modalAlert("保存成功", 'success');
                $("#btn_search").trigger("click");
            }
        });
    };

    //将库存换算成最小单位数  拆零
    function CalculationMinUnitNum(deptNum, minNum, zhyz) {
        return parseInt(deptNum) * parseInt(zhyz) + parseInt(minNum);
    }

    //将库存换算成最小单位数  不拆零
    function CalculationMinUnitNumNoOpen(deptNum, zhyz) {
        return parseInt(deptNum) * parseInt(zhyz);
    }

    //启用行内编辑框
    function EnableInlineEditBox() {
        var rowIds = $("#gridKCInfo").jqGrid('getDataIDs');//Grid加载完成开启行内编辑   1.先获取所有行Id  2.遍历调用editRow方法
        for (var i = 0; i < rowIds.length; i++) {
            $("#gridKCInfo").jqGrid('editRow', rowIds[i], true, null, null, null, null, function (callbackRowId) {     //true: when set to true we can use [Enter] key to save the row and [Esc] to cancel editing.
            });
        }
    }

    //结束盘点
    function newtouch_event_f3() {
        $.najax({
            type: "POST",
            url: "/PharmacyDrugStorage/EndInventory",
            dataType: "json",
            data: { pdId: $("#ddlRQ option:selected").attr('data-pdId') },
            success: function (ajaxresp) {
                $.modalAlert("盘点完成", 'success');
                GetPDSJ();//刷新盘点时间及药品信息
            }
        });
    }

    //取消盘点
    function newtouch_event_f7() {
        $.najax({
            type: "POST",
            url: "/PharmacyDrugStorage/CancelInventory",
            dataType: "json",
            data: { pdId: $("#ddlRQ option:selected").attr('data-pdId') },
            success: function (ajaxresp) {
                $.modalAlert("取消成功", 'success');
                GetPDSJ();
            }
        });
    }

</script>
